package com.tistory.admin.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * HTTPS->HTTP로 이동하면서 세션은 공유되지 않는 문제 조치 HTTPS 요청일 경우 쿠키에 세션 정보를 조작하는 역할
 */
public class HttpsRequestWrapper extends HttpServletRequestWrapper {
	private HttpServletResponse response = null;

	public HttpsRequestWrapper(HttpServletRequest request) {
		super(request);
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public HttpSession getSession() {
		HttpSession session = super.getSession();

		this.processSessionCookie(session);
		return session;
	}

	@Override
	public HttpSession getSession(boolean create) {
		HttpSession session = super.getSession(create);
		this.processSessionCookie(session);
		return session;
	}

	private void processSessionCookie(HttpSession session) {
		if (null == this.response || null == session)
			return;

		Object cookieOverWritten = this.getAttribute("COOKIE_OVERWRITTEN_FLAG");

		if (null == cookieOverWritten /* && isSecure() */
				&& this.isRequestedSessionIdFromCookie() && session.isNew()) {
			Cookie cookie = new Cookie("JSESSIONID", session.getId());
			cookie.setMaxAge(-1);
			String contextPath = this.getContextPath();
			if ((contextPath != null) && (contextPath.length() > 0)) {
				cookie.setPath(contextPath);
			} else {
				cookie.setPath("/");
			}
			this.response.addCookie(cookie);
			this.setAttribute("COOKIE_OVERWRITTEN_FLAG", "true");
		}
	}
}
